import 'dart:io';
import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/ui/test_function/test_function_view_model.dart';
import 'package:e_reception_flutter/ui/test_function/test_history_page.dart';
import 'package:e_reception_flutter/ui/test_function/test_scan_bind_hsn_id_page.dart';
import 'package:e_reception_flutter/ui/test_function/test_scan_id_page.dart';
import 'package:e_reception_flutter/ui/test_function/test_terminal_detail_page.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:qr_code_scanner/qr_code_scanner.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';

/// 扫码绑定hsn以及id页面
class HsnIdScanPage extends StatefulWidget {
  final String type;
  final String hsn;
  final bool updateFlag;
  ///路由名称
  static const String ROUTER = "HsnIdScanPage";
  static const String TYPE_HSN = "type_hsn";
  static const String TYPE_ID = "type_id";

  const HsnIdScanPage({Key key, this.type, this.hsn, this.updateFlag}) : super(key: key);

  @override
  _HsnIdScanPageState createState() => _HsnIdScanPageState();

  ///跳转方法
  static Future<String> navigatorPush(BuildContext context,String type, {String hsn, bool updateFlag}) {
    return RouterUtils.routeForFutureResult(
      context,
      HsnIdScanPage(
        type:type,
        hsn: hsn,
        updateFlag: updateFlag,
      ),
      routeName: HsnIdScanPage.ROUTER,
    );
  }
}

class _HsnIdScanPageState extends BaseState<HsnIdScanPage> {
  Barcode result;
  QRViewController controller;
  final GlobalKey qrKey = GlobalKey(debugLabel: 'QR');
  TestFunctionViewModel _viewModel;
  bool _scanFinish = false;
  @override
  void reassemble() {
    super.reassemble();
    if (Platform.isAndroid) {
      controller.pauseCamera();
    }
    controller.resumeCamera();
  }

  @override
  void initState() {
    super.initState();
    _viewModel = new TestFunctionViewModel(this);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: Stack(
        children: <Widget>[
          Container(child: _buildQrView(context)),
          Positioned(
            top: ScreenUtils.getStatusBarH(context),
            left: 0,
            child: GestureDetector(
              behavior: HitTestBehavior.translucent,
              onTap: () {
                Navigator.of(context).pop("");
              },
              child: _topLeftWidget(),
            ),
          ),
          Positioned(
            top: (ScreenUtils.screenH(context) - ScreenUtils.getBottomBarH(context)
                -ScreenUtils.getStatusBarH(context) - NAV_HEIGHT - 300)/2,
            left: 0,
            right: 0,
            child: Center(
              child: Text(
                "对准二维码，即可自动扫描",
                style: TextStyle(
                  color: const Color(0xFFD0E0F7),
                ),
              ),
            ),
          ),

          Positioned(
            bottom: 50,
            left: 0,
            right: 0,
            child: GestureDetector(
              behavior: HitTestBehavior.translucent,
              onTap: () async {
                await controller?.toggleFlash();
                setState(() {});
              },
              child: Center(
                child: Image.asset(
                  "images/icon_flash_light.png",
                  width: 50,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _topLeftWidget(){
    return ClickAnimateWidget(
      child: Container(
        width: 40,
        height: 44,
        alignment: Alignment.centerLeft,
        padding: const EdgeInsets.only(left: 15.6),
        child: Image.asset(
          "images/top_bar_back_ico.png",
          width: 9,
          color: VgColors.INPUT_BG_COLOR,
        ),
      ),
      scale: 1.4,
      onClick: () {
        // VgNavigatorUtils.pop(context);
        FocusScope.of(context).requestFocus(FocusNode());
        Navigator.of(context).maybePop();
      },
    );
  }

  Widget _buildQrView(BuildContext context) {
    // For this example we check how width or tall the device is and change the scanArea and overlay accordingly.
    // var scanArea = (MediaQuery.of(context).size.width < 400 ||
    //     MediaQuery.of(context).size.height < 400)
    //     ? 150.0
    //     : 300.0;
    var scanArea = 300.0;
    // To ensure the Scanner view is properly sizes after rotation
    // we need to listen for Flutter SizeChanged notification and update controller
    return QRView(
      key: qrKey,
      onQRViewCreated: _onQRViewCreated,
      overlay: QrScannerOverlayShape(
          borderColor:Color(0xFF1890FF),
          borderRadius: 0,
          borderLength: 30,
          borderWidth: 4,
          cutOutSize: scanArea),
    );
  }

  void _onQRViewCreated(QRViewController controller) {
    setState(() {
      this.controller = controller;
    });
    controller.scannedDataStream.listen((scanData) async{
      if(_scanFinish){
        return;
      }
      _scanFinish = true;
      if(HsnIdScanPage.TYPE_HSN == widget?.type){
        result = scanData;
        String code = result.code;
        print("scan result:" + code);
        String hsn = code.substring(code.indexOf("?testHsn=")+9, code.length);
        print("scan hsn:" + hsn);
        _viewModel.checkHsn(context, hsn, callback: (success, msg){
          if(success){
            if("该显示屏已绑定机身编码" == msg){
              RouterUtils.pop(context);
              TestTerminalDetailPage.navigatorPush(context, hsn, TestHistoryPage.ROUTER);
            }else{
              RouterUtils.pop(context);
              TestScanIdPage.navigatorPush(context, hsn, true);
            }
          }else{
            Future.delayed(Duration(milliseconds: 2000),(){
              _scanFinish = false;
            });
          }
        });
      }else if(HsnIdScanPage.TYPE_ID == widget?.type){
        result = scanData;
        String code = result.code;
        print("scan result:" + code);
        String id = code.substring(code.indexOf("?codeId=")+8, code.length);
        print("scan id:" + id);
        if(id.length > 12){
          VgToastUtils.toast(context, "请扫描正确的机身侧面二维码");
          Future.delayed(Duration(milliseconds: 2000),(){
            _scanFinish = false;
          });
          return;
        }
        _viewModel.checkId(context, id, callback: (success){
          if(success){
            RouterUtils.pop(context);
            TestScanBindHsnIdPage.navigatorPush(context, widget?.hsn, id, widget?.updateFlag);
          }else{
            Future.delayed(Duration(milliseconds: 2000),(){
              _scanFinish = false;
            });
          }
        });
      }
    });
  }

  @override
  void dispose() {
    controller?.dispose();
    super.dispose();
  }
}

